import { FrontNotifyClient } from './frontNotiyClient';
import { Logger } from '../utils/logger';
var webConfig = require("../../../webconfig.js");

export namespace FNS {
    export class FNCManager {
        private fnc: FrontNotifyClient;
        static Current: FNCManager = new FNCManager();
        constructor() {
            let fnsPort = webConfig.isHttps ? 8896 : 8897;
            let protocol = webConfig.isHttps ? "wss" : "ws";
            this.fnc = new FrontNotifyClient({
                fnsHostName: protocol + "://localhost",
                fnsPort: fnsPort,
                clientId: "localFBSClient"
            });
        }

        Notify<T>(data: IFNSMessage<T>) {
            if (this.fnc == null || this.fnc == undefined) throw new FNCException(this, "FNC 未初始化！");
            if (this.fnc.IsConnect == false) throw new FNCException(this, "FNS 未连接！");

            let msg = {
                type: "innerMessage",
                content: data
            }
            this.fnc.Notify(msg);
        }
    }

    class FNCException extends Error {
        private innerException;
        message;
        constructor(private module: any, message: string) {
            super(message);
            this.module = {
                name: "FNCException"
            };
            new Logger().getLogger('error').error(this.module.name, this);
        }
        get Message() { return this.message; }
        get Module() { return this.module.toString(); }
        get InnerException() { return this.innerException; }
    }

    export interface IFNSMessage<T> {
        headers: { name: string; };
        status: number;
        body: T
    }

    interface SoldOutMessageData {
        id: string;
        isSoldOut: boolean;
        soldOutMode: string;
        quantity?: number;
    }

    export class SoldOutMessage implements IFNSMessage<SoldOutMessageData[]> {
        headers;
        status = 0;
        body: SoldOutMessageData[] = []
        constructor(body: SoldOutMessageData[]) {
            this.headers = {
                name: "soldOut"
            }
            this.body = body;
        }
    }
}